/*
 * @Author: wangyongcun@persagy.com
 * @Date: 2025-03-21 17:57:20
 * @LastEditTime: 2025-03-22 18:46:42
 * @FilePath: \vite-admin\src\plugins\loading\injectAppLoadingPlugin.ts
 * @Description:
 *
 */
import type { PluginOption } from 'vite';

import fsp from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

/**
 * 用于获取loading的html模板
 */
async function getLoadingRawByHtmlTemplate(loadingTemplate?: string) {
  let appLoadingPath = '';
  if (!loadingTemplate) {
    const __dirname = fileURLToPath(new URL('.', import.meta.url));
    appLoadingPath = join(__dirname, './default-loading.html');
  } else {
    appLoadingPath = join(process.cwd(), loadingTemplate);
  }
  return await fsp.readFile(appLoadingPath, 'utf8');
}


/**
 * 用于生成将loading样式注入到项目中
 * 为多app提供loading样式，无需在每个 app -> index.html单独引入
 */
async function injectAppLoadingPlugin(
  loadingTemplate?: string
): Promise<PluginOption | undefined> {
  let loadingHtml = await getLoadingRawByHtmlTemplate(loadingTemplate);
  return {
    enforce: 'pre',
    name: 'inject-app-loading',
    transformIndexHtml(html, ctx) {
      const VITE_APP_TITLE = ctx.server?.config.env.VITE_APP_TITLE || '';
      loadingHtml = loadingHtml.replace(/<%=?\s*VITE_APP_TITLE\s*%>/g, VITE_APP_TITLE);
      const re = /<body\s*>/;
      html = html.replace(re, `<body>${loadingHtml}`);
      return html;
    },
  };
}

export { injectAppLoadingPlugin };
